<template>
	<div class="card content-box">
		<a-drawer :width="500" title="查看权限" placement="right" :visible="visible" @close="onClose">
			<a-tree
				v-model:expandedKeys="expandedKeys"
				v-model:selectedKeys="selectedKeys"
				v-model:checkedKeys="checkedKeys"
				checkable
				:tree-data="treeData"
				:field-names="fieldNames"
				@select="treeSelect"
			>
				<template #title="{ meta }">
					{{ meta.title }}
				</template>
			</a-tree>
		</a-drawer>

		<a-table :columns="columns" :data-source="list" style="width: 100%" :rowKey="(record: TreeNode) => record.name">
			<template #bodyCell="{ column, index }">
				<template v-if="column.key === 'action'">
					<span>
						<a @click="showDrawer(index)">查看权限</a>
					</span>
				</template>
			</template>
		</a-table>
	</div>
</template>

<script setup lang="ts" name="menuAuth">
import { ref, watch, computed } from "vue";
import { useAuthStore } from "@/stores/modules/auth";
import { getAuthHority } from "@/api/modules/role";
import { getFlatArr } from "@/utils/util";

const authStore = useAuthStore();
const menuList = computed(() => authStore.authMenuListGet);

// 展开指定的树节点
const expandedKeys = ref<string[]>(["/menu/menu2"]);
// 设置选中的树节点
const selectedKeys = ref<string[]>([]);
// 选中复选框的树节点
const checkedKeys = ref<string[]>([]);
// 替换 treeNode 中 title,key,children 字段为 treeData 中对应的字段
const fieldNames: any = {
	children: "children",
	key: "path"
};

interface TreeNode {
	name: string;
	path: string;
	component?: string;
	children?: TreeNode[];
}

const treeData = menuList.value as TreeNode[];

// 树节点样式清除
const treeSelect = () => {
	selectedKeys.value = [];
};

watch(expandedKeys, () => {
	console.log("expandedKeys", expandedKeys);
});
watch(selectedKeys, () => {
	console.log("selectedKeys", selectedKeys);
});
watch(checkedKeys, () => {
	console.log("checkedKeys", checkedKeys);
});

const columns = [
	{
		title: "角色名称",
		dataIndex: "name",
		key: "name"
	},
	{
		title: "操作",
		dataIndex: "action",
		key: "action"
	}
];
const list = [
	{
		name: "admin"
	},
	{
		name: "user"
	}
];

const visible = ref<boolean>(false);

const showDrawer = async (id: number) => {
	const res: any = await getAuthHority(id);
	checkedKeys.value = getFlatArr(res.data).map((item: any) => item.path);
	visible.value = true;
};

const onClose = () => {
	visible.value = false;
};
</script>

<style scoped lang="less"></style>
